package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLevelDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyTimeDetail;
import com.ybkj.daijia.server.service.ChargeStartTimeService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLevelDetailService;
import com.ybkj.daijia.server.service.DriverLevelMoneyTimeDetailService;
import com.ybkj.daijia.server.service.DriverLevelService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "driverlevel")
public class DriverLevelController {

    @Autowired
    private DriverLevelService driverLevelService;
    @Autowired
    private DriverLevelDetailService driverLevelDetailService;
    @Autowired
    private DriverLevelMoneyTimeDetailService driverLevelMoneyTimeDetailService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ChargeStartTimeService chargeStartTimeService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false, value = "name") String name) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("level")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driverlevel/list");

            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();

            Page<DriverLevel> page = driverLevelService.queryAll(principal.getCompanyId(), name);

            mv.addObject("page", page);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(Integer type) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("level")) {
            ModelAndView mv = new ModelAndView();

            if (null == type || type.equals(0)) {
                mv.setViewName("driverlevel/add");
            } else {
                mv.setViewName("driverlevel/addbymoney");
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(DriverLevel driverLevel, Model model) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("level")) {
            driverLevel.setCompanyId(principal.getCompanyId());

            if (driverLevel.getType() == 0) {
                for (DriverLevelDetail driverLevelDetail : driverLevel.getDriverLevelDetails()) {
                    int a = driverLevelDetail.getCommission().compareTo(BigDecimal.ZERO);
                    int b = driverLevelDetail.getMoney().compareTo(BigDecimal.ZERO);
                    int c = driverLevelDetail.getMinCommission().compareTo(BigDecimal.ZERO);
                    int d = driverLevelDetail.getLowCommission().compareTo(BigDecimal.ZERO);
                    int e = driverLevelDetail.getMinMoney().compareTo(BigDecimal.ZERO);
                    int f = driverLevelDetail.getLowMoney().compareTo(BigDecimal.ZERO);

                    if (a == -1 || b == -1 || c == -1 || d == -1 || e == -1 || f == -1) {
                        return "redirect:list";
                    }
                }
            }
            if (driverLevel.getType() == 1) {
                for (DriverLevelMoneyTimeDetail driverLevelMoneyTimeDetail : driverLevel
                    .getDriverLevelMoneyTimeDetails()) {
                    for (DriverLevelMoneyDetail driverLevelMoneyDetail : driverLevelMoneyTimeDetail
                        .getDriverLevelMoneyDetails()) {
                        if (driverLevelMoneyDetail.getFromMoney() != null
                            && driverLevelMoneyDetail.getFromMoney().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getMoneyUnit() != null
                            && driverLevelMoneyDetail.getMoneyUnit().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getToMoney() != null
                            && driverLevelMoneyDetail.getToMoney().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getCommission() != null
                            && driverLevelMoneyDetail.getCommission().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getMoney() != null
                            && driverLevelMoneyDetail.getMoney().compareTo(BigDecimal.ZERO) == -1) {
                            return "redirect:list";
                        }
                    }
                }
            }

            driverLevelService.insertRecord(driverLevel);

            String detail = "【%s】新增了提成【" + driverLevel.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "createTimeMoney", method = RequestMethod.POST)
    public @ResponseBody
    Result<DriverLevel> createTimeMoney(DriverLevel driverLevel) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<DriverLevel> result = new Result<DriverLevel>();

        if (subject.isPermitted("level")) {
            driverLevel.setCompanyId(principal.getCompanyId());

            driverLevelService.insertMoneyRecord(driverLevel);

            String detail = "【%s】新增了提成【" + driverLevel.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
        }

        return result;
    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "type") Integer type) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("level")) {
            ModelAndView mv = new ModelAndView();

            DriverLevel local = driverLevelService.findOne(id);

            mv.addObject("driverLevel", local);

            if (null == type) {
                if (null == local.getType() || local.getType().equals(0)) {
                    local.setDriverLevelDetails(
                        driverLevelDetailService.findByDriverLevel(local.getId()));
                    mv.setViewName("driverlevel/edit");
                } else {
                    local.setDriverLevelMoneyTimeDetails(
                        driverLevelMoneyTimeDetailService.findByDriverLevel(local.getId()));
                    mv.setViewName("driverlevel/editbymoney");
                }
            } else {
                if (type == 0) {
                    local.setDriverLevelDetails(
                        driverLevelDetailService.findByDriverLevel(local.getId()));
                    mv.setViewName("driverlevel/edit");
                } else {
                    local.setDriverLevelMoneyTimeDetails(
                        driverLevelMoneyTimeDetailService.findByDriverLevel(local.getId()));
                    mv.setViewName("driverlevel/editbymoney");
                }
            }

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(DriverLevel driverLevel, Model model) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("level")) {

            if (driverLevel.getType() == 0) {
                for (DriverLevelDetail driverLevelDetail : driverLevel.getDriverLevelDetails()) {
                    int a = driverLevelDetail.getCommission().compareTo(BigDecimal.ZERO);
                    int b = driverLevelDetail.getMoney().compareTo(BigDecimal.ZERO);
                    int c = driverLevelDetail.getMinCommission().compareTo(BigDecimal.ZERO);
                    int d = driverLevelDetail.getLowCommission().compareTo(BigDecimal.ZERO);
                    int e = driverLevelDetail.getMinMoney().compareTo(BigDecimal.ZERO);
                    int f = driverLevelDetail.getLowMoney().compareTo(BigDecimal.ZERO);

                    if (a == -1 || b == -1 || c == -1 || d == -1 || e == -1 || f == -1) {
                        return "redirect:list";
                    }
                }
            }
            if (driverLevel.getType() == 1) {
                for (DriverLevelMoneyTimeDetail driverLevelMoneyTimeDetail : driverLevel
                    .getDriverLevelMoneyTimeDetails()) {
                    for (DriverLevelMoneyDetail driverLevelMoneyDetail : driverLevelMoneyTimeDetail
                        .getDriverLevelMoneyDetails()) {
                        if (driverLevelMoneyDetail.getFromMoney() != null
                            && driverLevelMoneyDetail.getFromMoney().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getMoneyUnit() != null
                            && driverLevelMoneyDetail.getMoneyUnit().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getToMoney() != null
                            && driverLevelMoneyDetail.getToMoney().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getCommission() != null
                            && driverLevelMoneyDetail.getCommission().compareTo(BigDecimal.ZERO)
                            == -1) {
                            return "redirect:list";
                        }
                        if (driverLevelMoneyDetail.getMoney() != null
                            && driverLevelMoneyDetail.getMoney().compareTo(BigDecimal.ZERO) == -1) {
                            return "redirect:list";
                        }
                    }
                }
            }

            driverLevelService.updateByPrimaryKey(driverLevel);

            String detail = "【%s】修改了提成【" + driverLevel.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "updateTimeMoney", method = RequestMethod.POST)
    public @ResponseBody
    Result<DriverLevel> updateTimeMoney(DriverLevel driverLevel) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<DriverLevel> result = new Result<DriverLevel>();

        if (subject.isPermitted("level")) {

            driverLevelService.updateMoneyRecord(driverLevel);

            String detail = "【%s】修改了提成【" + driverLevel.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
        }

        return result;
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("level")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                DriverLevel driverLevel = driverLevelService.findOne(id);
                if (null != driverLevel) {
                    //TODO 这里需要优化
//					if(!CollectionUtils.isEmpty(driverLevel.getDrivers())){
//						result.setSuccess(false);
//						result.setMessage("'"+driverLevel.getName()+"'被司机引用，不能删除");
//					}
//					else{
                    String detail = "【%s】删除了提成【" + driverLevel.getName() + "】";

                    driverLevelService.delete(driverLevel);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                    //}
                } else {
                    result.setSuccess(false);
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setSuccess(false);
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

